
from whiff.middleware import misc
import time
from whiff import gateway
from whiff import resolver
from whiff import whiffenv

class getItem(misc.utility):
    
    def __init__(self, page, elsePage=None):
        self.page = page
        self.elsePage = elsePage
        
    def __call__(self, env, start_response):
        env = env.copy()
        is_stub = env.get("STUB")
        if is_stub:
            env = self.stub(env)
        else:
            env = self.update(env)
        if env.get("Found"):
            return self.deliver_page(self.page, env, start_response)
        else:
            assert self.elsePage is not None, "could not find %s and elsePage not defined" % repr(env["Name"])
            env["error_message"] = "The page %s does not exist: please create it" % repr(env["Name"])
            env["Title"] = ""
            env["Summary"] = ""
            env["Text"] = ""
            env["TextSource"] = ""
            env["Note"] = ""
            env["TimeStamp"] = time.ctime()
            return self.deliver_page(self.elsePage, env, start_response)
    
    def stub(self, env):
        env["Name"] = "STUB_WIKI_ITEM_NAME"
        env["Title"] = "Stub Title"
        env["Summary"] = "Stub Summary"
        text = "This is just some stub text for testing purposes. Here is a [[Link]] notation."
        env["Text"] = addLinks(text)
        env["TextSource"] = text
        env["Note"] = "Stub Note." 
        env["TimeStamp"] = time.ctime()
        return env

    def update(self, env):
        env = resolver.process_cgi(env, parse_cgi=True)
        name = whiffenv.cgiGet(env, "Name", "").strip()
        if not name:
            raise resolver.ModuleRootResolutionException, "cannot find wiki item with empty name"
        storage = gateway.getResource(env, ["storage"])
        if storage is None:
            storage = {}
        if not storage.has_key(name):
            #raise resolver.ModuleRootResolutionException, "no page found with this name: "+repr(name)
            env["Found"] = False # not found sentinel
            env["Name"] = name
            return env
        env["Found"] = True
        data = storage[name]
        env["Name"] = data["Name"]
        env["Title"] = data["Title"]
        env["Summary"] = data["Summary"]
        text = data["Text"]
        env["Text"] = addLinks(text)
        env["TextSource"] = text
        env["Note"] = data["Note"]
        env["TimeStamp"] = time.ctime()
        return env

def addLinks(text):
    L = []
    startSplit = text.split("[[")
    L.append(startSplit[0])
    for chunk in startSplit[1:]:
        endSplit = chunk.split("]]")
        if len(endSplit)<2:
            L.extend(endSplit)
        else:
            name = endSplit[0]
            remainder = endSplit[1:]
            L.append('<a href="viewPage?Name=%s"> [%s] </a>' % (name, name))
            L.extend(remainder)
    return "".join(L)

__middleware__ = getItem
